<template>
  <div class="region-contribution">
    <el-card>
      <div slot="header" class="clearfix">
        <span class="page-title"><i class="el-icon-data-line"></i> 各区域每月贡献值</span>
        <div class="header-actions">
          <el-button
            class="refresh-btn"
            type="primary"
            icon="el-icon-refresh"
            @click="refreshData">
            <span class="btn-text">刷新数据</span>
          </el-button>
          <el-button
            class="export-btn"
            type="success"
            icon="el-icon-download"
            @click="exportDataFunc">
            <span class="btn-text">导出数据</span>
          </el-button>
        </div>
      </div>

      <!-- 筛选条件 -->
      <!-- <div class="filter-section">
        <el-form :inline="true" :model="filterForm" class="demo-form-inline">
          <el-form-item label="统计月份">
            <el-date-picker
              v-model="filterForm.month"
              type="month"
              placeholder="选择月份"
              format="yyyy-MM"
              value-format="yyyy-MM"
              :clearable="false">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="区域筛选">
            <el-select v-model="filterForm.regionId" placeholder="选择区域" clearable>
              <el-option label="全部区域" :value="null"></el-option>
              <el-option
                v-for="region in regionList"
                :key="region.id"
                :label="region.name"
                :value="region.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div> -->

      <!-- 统计概览 -->
      <div class="overview-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="overview-card total">
              <div class="card-icon">
                <i class="el-icon-data-line"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总积分</div>
                <div class="card-value">{{ totalPoints.toLocaleString() }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="overview-card average">
              <div class="card-icon">
                <i class="el-icon-pie-chart"></i>
              </div>
              <div class="card-content">
                <div class="card-title">平均积分</div>
                <div class="card-value">{{ averagePoints.toLocaleString() }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="overview-card top">
              <div class="card-icon">
                <i class="el-icon-trophy"></i>
              </div>
              <div class="card-content">
                <div class="card-title">最高积分</div>
                <div class="card-value">{{ maxPoints.toLocaleString() }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="overview-card regions">
              <div class="card-icon">
                <i class="el-icon-office-building"></i>
              </div>
              <div class="card-content">
                <div class="card-title">参与区域</div>
                <div class="card-value">{{ regionCount }} 个</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 图表展示 -->
      <div class="chart-section">
        <el-card>
          <div slot="header" class="clearfix">
            <span>各区域代理当月积分贡献</span>
            <div class="chart-controls">
              <el-radio-group v-model="chartType" @change="handleChartTypeChange">
                <el-radio-button label="bar">柱状图</el-radio-button>
                <el-radio-button label="line">折线图</el-radio-button>
                <el-radio-button label="pie">饼图</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div id="contributionChart" style="height: 400px;" v-loading="chartLoading"></div>
        </el-card>
      </div>

      <!-- 详细数据表格 -->
      <div class="table-section">
        <el-card>
          <div slot="header" class="clearfix">
            <span>区域贡献值详情</span>
            <div class="table-controls">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索区域名称"
                prefix-icon="el-icon-search"
                style="width: 200px; margin-right: 10px;"
                @input="handleSearchKeyword">
              </el-input>
              <el-button type="text" @click="sortByPoints">
                <i class="el-icon-sort"></i> 按积分排序
              </el-button>
            </div>
          </div>

          <!-- 使用可配置表格组件 -->
          <configurable-table
            :columns="tableColumns"
            :data="filteredTableData"
            :loading="tableLoading"
            :show-pagination="true"
            :current-page.sync="pagination.current"
            :page-size.sync="pagination.size"
            :pagination-total="pagination.total"
            :default-sort="{prop: 'points', order: 'descending'}"
            border>
            <!-- 排名列 -->
            <template #rank="{ row }">
              <el-tag :type="getRankTag(row.rank)" size="small">
                {{ row.rank }}
              </el-tag>
            </template>

            <!-- 区域名称列 -->
            <template #regionName="{ row }">
              <div class="region-info">
                <i class="el-icon-office-building"></i>
                <span>{{ row.regionName }}</span>
              </div>
            </template>

            <!-- 区域代理列 -->
            <template #agentName="{ row }">
              <div class="agent-info">
                <i class="el-icon-user"></i>
                <span>{{ row.agentName }}</span>
              </div>
            </template>

            <!-- 当月积分列 -->
            <template #points="{ row }">
              <div class="points-display">
                <span class="points-value">{{ row.points.toLocaleString() }}</span>
                <el-tag
                  :type="getPointsTag(row.points)"
                  size="mini"
                  class="points-tag">
                  {{ getPointsLevel(row.points) }}
                </el-tag>
              </div>
            </template>

            <!-- 管理商家数列 -->
            <template #merchantCount="{ row }">
              <el-tag type="info" size="small">{{ row.merchantCount || 0 }}</el-tag>
            </template>

            <!-- 管理业务员数列 -->
            <template #salesmanCount="{ row }">
              <el-tag type="success" size="small">{{ row.salesmanCount || 0 }}</el-tag>
            </template>

            <!-- 增长率列 -->
            <template #growthRate="{ row }">
              <span :class="row.growthRate >= 0 ? 'growth-positive' : 'growth-negative'">
                {{ row.growthRate >= 0 ? '+' : '' }}{{ row.growthRate }}%
              </span>
            </template>

            <!-- 操作列 -->
            <template #actions="{ row }">
              <el-button size="mini" icon="el-icon-view" @click="handleViewDetail(row)">详情</el-button>
              <el-button size="mini" type="primary" icon="el-icon-trend-charts" @click="handleViewTrend(row)">趋势</el-button>
            </template>
          </configurable-table>
        </el-card>
      </div>
    </el-card>

    <!-- 区域详情对话框 -->
    <el-dialog
      title="区域贡献值详情"
      :visible.sync="detailDialogVisible"
      width="900px"
      :close-on-click-modal="false"
      custom-class="view-dialog">
      <div class="detail-content" v-if="selectedRegion">
        <!-- 头部统计卡片 -->
        <div class="detail-header-stats">
          <el-row :gutter="15">
            <el-col :span="6">
              <div class="stat-card primary">
                <div class="stat-icon">
                  <i class="el-icon-trophy"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-label">排名</div>
                  <div class="stat-value">第{{ selectedRegion.rank }}名</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card success">
                <div class="stat-icon">
                  <i class="el-icon-data-line"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-label">当月积分</div>
                  <div class="stat-value">{{ selectedRegion.points.toLocaleString() }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card warning">
                <div class="stat-icon">
                  <i class="el-icon-shopping-bag-2"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-label">订单数量</div>
                  <div class="stat-value">{{ selectedRegion.orderCount }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card info">
                <div class="stat-icon">
                  <i class="el-icon-wallet"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-label">交易金额</div>
                  <div class="stat-value">¥{{ (selectedRegion.totalAmount / 100).toFixed(0) }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 详细信息卡片 -->
        <el-row :gutter="20" class="detail-cards-row">
          <el-col :span="12">
            <el-card class="detail-info-card" shadow="hover">
              <div slot="header" class="card-header">
                <i class="el-icon-office-building"></i>
                <span>基本信息</span>
              </div>
              <div class="info-list">
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-location-outline"></i>
                    <span>区域名称</span>
                  </div>
                  <div class="info-value">{{ selectedRegion.regionName }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-user"></i>
                    <span>区域代理</span>
                  </div>
                  <div class="info-value">{{ selectedRegion.agentName }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-phone"></i>
                    <span>代理电话</span>
                  </div>
                  <div class="info-value">{{ selectedRegion.agentPhone || '未提供' }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-message"></i>
                    <span>代理邮箱</span>
                  </div>
                  <div class="info-value">{{ selectedRegion.agentEmail || '未提供' }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="detail-info-card" shadow="hover">
              <div slot="header" class="card-header">
                <i class="el-icon-data-analysis"></i>
                <span>贡献数据</span>
              </div>
              <div class="info-list">
                <div class="info-item highlight-item">
                  <div class="info-label">
                    <i class="el-icon-star-on"></i>
                    <span>当月积分</span>
                  </div>
                  <div class="info-value highlight-value">
                    {{ selectedRegion.points.toLocaleString() }}
                    <el-tag
                      :type="getPointsTag(selectedRegion.points)"
                      size="mini"
                      style="margin-left: 8px;">
                      {{ getPointsLevel(selectedRegion.points) }}
                    </el-tag>
                  </div>
                </div>
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-shop"></i>
                    <span>管理商家数</span>
                  </div>
                  <div class="info-value">
                    <el-tag type="info" size="small">{{ selectedRegion.merchantCount || 0 }} 个</el-tag>
                  </div>
                </div>
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-user-solid"></i>
                    <span>管理业务员数</span>
                  </div>
                  <div class="info-value">
                    <el-tag type="success" size="small">{{ selectedRegion.salesmanCount || 0 }} 个</el-tag>
                  </div>
                </div>
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-trend-charts"></i>
                    <span>增长率</span>
                  </div>
                  <div class="info-value">
                    <span :class="selectedRegion.growthRate >= 0 ? 'growth-positive' : 'growth-negative'">
                      <i :class="selectedRegion.growthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                      {{ selectedRegion.growthRate >= 0 ? '+' : '' }}{{ selectedRegion.growthRate }}%
                    </span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 趋势图表 -->
        <el-card class="trend-chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <i class="el-icon-data-line"></i>
            <span>月度趋势</span>
          </div>
          <div id="trendChart" style="height: 240px;"></div>
        </el-card>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false" icon="el-icon-close">关闭</el-button>
        <el-button type="primary" @click="handleViewTrend(selectedRegion)" icon="el-icon-trend-charts">查看详细趋势</el-button>
      </div>
    </el-dialog>

    <!-- 趋势分析对话框 -->
    <el-dialog
      title="区域贡献值趋势分析"
      :visible.sync="trendDialogVisible"
      width="1000px"
      :close-on-click-modal="false"
      custom-class="trend-dialog">
      <div class="trend-content" v-if="selectedRegion">
        <!-- 趋势头部 -->
        <div class="trend-header">
          <div class="trend-title-section">
            <i class="el-icon-data-analysis"></i>
            <h3>{{ selectedRegion.regionName }} - 贡献值趋势分析</h3>
          </div>
          <div class="trend-controls">
            <el-radio-group v-model="trendPeriod" @change="handleTrendPeriodChange" size="small">
              <el-radio-button label="3months">
                <i class="el-icon-date"></i> 近3个月
              </el-radio-button>
              <el-radio-button label="6months">
                <i class="el-icon-date"></i> 近6个月
              </el-radio-button>
              <el-radio-button label="12months">
                <i class="el-icon-date"></i> 近12个月
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <!-- 趋势图表 -->
        <el-card class="trend-chart-wrapper" shadow="hover">
          <div id="trendAnalysisChart" style="height: 400px;"></div>
        </el-card>

        <!-- 趋势分析统计卡片 -->
        <div class="trend-analysis">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="analysis-card average">
                <div class="analysis-icon">
                  <i class="el-icon-pie-chart"></i>
                </div>
                <div class="analysis-content">
                  <div class="analysis-title">平均积分</div>
                  <div class="analysis-value">{{ trendAnalysis.averagePoints.toLocaleString() }}</div>
                  <div class="analysis-desc">统计周期内平均值</div>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="analysis-card highest">
                <div class="analysis-icon">
                  <i class="el-icon-trophy"></i>
                </div>
                <div class="analysis-content">
                  <div class="analysis-title">最高积分</div>
                  <div class="analysis-value">{{ trendAnalysis.maxPoints.toLocaleString() }}</div>
                  <div class="analysis-desc">统计周期内峰值</div>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="analysis-card growth">
                <div class="analysis-icon">
                  <i :class="trendAnalysis.growthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                </div>
                <div class="analysis-content">
                  <div class="analysis-title">增长率</div>
                  <div class="analysis-value" :class="trendAnalysis.growthRate >= 0 ? 'growth-positive' : 'growth-negative'">
                    {{ trendAnalysis.growthRate >= 0 ? '+' : '' }}{{ trendAnalysis.growthRate }}%
                  </div>
                  <div class="analysis-desc">相比周期起点</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="trendDialogVisible = false" icon="el-icon-close">关闭</el-button>
        <el-button type="primary" icon="el-icon-download">导出报告</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getContributionData } from '@/api/aggregation'

export default {
  name: 'RegionContribution',
  data() {
    return {
      loading: false,
      chartLoading: false,
      tableLoading: false,
      filterForm: {
        month: this.getCurrentMonth(),
        regionId: null
      },
      regionList: [
        { id: 1, name: '华东区域' },
        { id: 2, name: '华南区域' },
        { id: 3, name: '华北区域' },
        { id: 4, name: '西南区域' },
        { id: 5, name: '东北区域' },
        { id: 6, name: '西北区域' }
      ],
      chartType: 'bar',
      searchKeyword: '',
      tableData: [],
      filteredTableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 表格列配置
      tableColumns: [
        {
          prop: 'rank',
          label: '排名',
          minWidth: 80,
          align: 'center',
          slot: 'rank'
        },
        {
          prop: 'regionName',
          label: '区域名称',
          minWidth: 150,
          slot: 'regionName'
        },
        {
          prop: 'agentName',
          label: '区域代理',
          minWidth: 120,
          slot: 'agentName'
        },
        {
          prop: 'points',
          label: '当月积分',
          minWidth: 120,
          sortable: true,
          slot: 'points'
        },
        {
          prop: 'merchantCount',
          label: '管理商家数',
          minWidth: 120,
          sortable: true,
          slot: 'merchantCount'
        },
        {
          prop: 'salesmanCount',
          label: '管理业务员数',
          minWidth: 130,
          sortable: true,
          slot: 'salesmanCount'
        },
        {
          prop: 'orderCount',
          label: '订单数量',
          minWidth: 100,
          sortable: true
        },
        {
          prop: 'totalAmount',
          label: '交易金额',
          minWidth: 120,
          sortable: true,
          formatter: (row) => `¥${(row.totalAmount / 100).toFixed(2)}`
        },
        {
          prop: 'growthRate',
          label: '增长率',
          minWidth: 100,
          slot: 'growthRate'
        },
        {
          prop: 'lastUpdateTime',
          label: '最后更新时间',
          minWidth: 180
        },
        {
          label: '操作',
          minWidth: 150,
          fixed: 'right',
          slot: 'actions'
        }
      ],
      // 详情对话框
      detailDialogVisible: false,
      selectedRegion: null,
      // 趋势对话框
      trendDialogVisible: false,
      trendPeriod: '6months',
      trendAnalysis: {
        averagePoints: 0,
        maxPoints: 0,
        growthRate: 0
      }
    }
  },
  computed: {
    totalPoints() {
      return this.tableData.reduce((sum, item) => sum + item.points, 0)
    },
    averagePoints() {
      return this.tableData.length > 0 ? Math.round(this.totalPoints / this.tableData.length) : 0
    },
    maxPoints() {
      return this.tableData.length > 0 ? Math.max(...this.tableData.map(item => item.points)) : 0
    },
    regionCount() {
      return this.tableData.length
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 获取当前月份
    getCurrentMonth() {
      const now = new Date()
      return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
    },

    // 加载数据
    async loadData() {
      this.loading = true
      this.chartLoading = true
      this.tableLoading = true

      try {
        // 只调用一次接口，避免重复请求
        const contributionData = await this.loadRegionData()
        await this.loadTableData(contributionData)
        this.renderChart()
      } catch (error) {
        Logger.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
        this.chartLoading = false
        this.tableLoading = false
      }
    },

    // 加载区域数据
    async loadRegionData() {
      try {
        Logger.log('=== 加载区域贡献数据 ===')
        const response = await getContributionData()
        Logger.log('区域贡献数据API响应:', response)

        if (response.code === 0) {
          return response.data || []
        } else {
          Logger.warn('区域贡献数据为空')
          return []
        }
      } catch (error) {
        Logger.error('加载区域贡献数据失败:', error)
        return []
      }
    },

    // 加载表格数据
    async loadTableData(contributionData) {
      try {
        // 使用传入的数据，不再重复调用接口

        // 处理API返回的数据格式
        if (contributionData && contributionData.regionNames) {
          // 合并相同区域的数据
          const regionMap = new Map()

          contributionData.regionNames.forEach((regionName, index) => {
            const merchantCount = contributionData.merchantCounts[index] || 0
            const salesmanCount = contributionData.salesmanCounts[index] || 0

            if (regionMap.has(regionName)) {
              // 合并相同区域的数据
              const existing = regionMap.get(regionName)
              existing.merchantCount += merchantCount
              existing.salesmanCount += salesmanCount
            } else {
              // 新增区域数据
              regionMap.set(regionName, {
                regionName: regionName,
                merchantCount: merchantCount,
                salesmanCount: salesmanCount,
                points: (merchantCount * 1000) + (salesmanCount * 500) // 模拟积分计算
              })
            }
          })

          // 转换为表格格式
          this.tableData = Array.from(regionMap.values()).map((item, index) => ({
            id: index + 1,
            rank: index + 1,
            regionName: item.regionName,
            agentName: item.regionName.replace('区域代理', ''),
            agentPhone: '',
            agentEmail: '',
            points: item.points,
            orderCount: item.merchantCount * 10 + item.salesmanCount * 5, // 模拟订单数量
            totalAmount: item.points * 100, // 模拟交易金额（分为单位）
            growthRate: Math.floor(Math.random() * 20) - 10, // 模拟增长率 -10% 到 +10%
            lastUpdateTime: new Date().toLocaleString(),
            merchantCount: item.merchantCount,
            salesmanCount: item.salesmanCount
          }))
        } else {
          // 兼容旧数据格式
          this.tableData = contributionData.map((item, index) => ({
            id: item.regionId || item.id || index + 1,
            rank: index + 1,
            regionName: item.regionName || item.name || `区域${index + 1}`,
            agentName: item.agentName || item.agent || '区域代理',
            agentPhone: item.agentPhone || item.phone || '',
            agentEmail: item.agentEmail || item.email || '',
            points: item.points || item.contribution || 0,
            orderCount: item.orderCount || item.orders || 0,
            totalAmount: item.totalAmount || item.amount || 0,
            growthRate: item.growthRate || item.growth || 0,
            lastUpdateTime: item.lastUpdateTime || item.updateTime || new Date().toLocaleString()
          }))
        }

        // 按积分排序
        this.tableData.sort((a, b) => b.points - a.points)

        // 更新排名
        this.tableData.forEach((item, index) => {
          item.rank = index + 1
        })

        this.filteredTableData = [...this.tableData]
        this.pagination.total = this.tableData.length

        Logger.log('处理后的表格数据:', this.tableData)
      } catch (error) {
        Logger.error('加载表格数据失败:', error)
        this.tableData = []
        this.filteredTableData = []
        this.pagination.total = 0
      }
    },

    // 渲染图表
    renderChart() {
      const chartDom = document.getElementById('contributionChart')
      if (!chartDom) return

      const myChart = echarts.init(chartDom)

      // 按积分排序
      const sortedData = [...this.tableData].sort((a, b) => b.points - a.points)

      let option = {}

      if (this.chartType === 'bar') {
        option = {
          title: {
            text: '各区域代理当月积分贡献',
            left: 'center',
            textStyle: {
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: (params) => {
              const data = params[0]
              return `${data.name}<br/>积分: ${data.value.toLocaleString()}<br/>排名: ${data.dataIndex + 1}`
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: sortedData.map(item => item.regionName),
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '积分数量',
            nameTextStyle: {
              color: '#666'
            }
          },
          series: [{
            data: sortedData.map(item => item.points),
            type: 'bar',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#a0cfff' },
                  { offset: 0.5, color: '#409eff' },
                  { offset: 1, color: '#409eff' }
                ])
              }
            }
          }]
        }
      } else if (this.chartType === 'line') {
        option = {
          title: {
            text: '各区域代理当月积分贡献趋势',
            left: 'center',
            textStyle: {
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: sortedData.map(item => item.regionName),
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '积分数量'
          },
          series: [{
            data: sortedData.map(item => item.points),
            type: 'line',
            smooth: true,
            lineStyle: {
              color: '#409eff',
              width: 3
            },
            itemStyle: {
              color: '#409eff'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ])
            }
          }]
        }
      } else if (this.chartType === 'pie') {
        option = {
          title: {
            text: '各区域代理积分占比',
            left: 'center',
            textStyle: {
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: sortedData.map(item => item.regionName)
          },
          // 饼图不需要坐标轴，明确设置为空
          xAxis: {
            show: false
          },
          yAxis: {
            show: false
          },
          grid: {
            show: false
          },
          series: [{
            name: '积分贡献',
            type: 'pie',
            radius: '50%',
            center: ['50%', '60%'],
            data: sortedData.map(item => ({
              value: item.points,
              name: item.regionName
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        }
      }

      // 使用 notMerge: true 完全替换配置，避免不同图表类型配置冲突
      myChart.setOption(option, true)

      // 响应式调整
      window.addEventListener('resize', () => {
        myChart.resize()
      })
    },

    // 刷新数据
    refreshData() {
      this.$message.success('数据已刷新')
      this.loadData()
    },

    // 导出数据
    exportDataFunc() {
      try {
        // 检查是否有数据
        if (!this.filteredTableData || this.filteredTableData.length === 0) {
          this.$message.warning('暂无数据可导出')
          return
        }

        // 使用转换器将表格列配置转换为导出列配置
        const exportColumns = this.$convertTableColumnsToExport(
          this.tableColumns,
          {
            // 为使用了 slot 的列提供格式化函数
            rank: (value) => value,
            regionName: (value) => value,
            agentName: (value) => value,
            points: (value) => value.toLocaleString(),
            merchantCount: (value) => value || 0,
            salesmanCount: (value) => value || 0,
            growthRate: (value) => `${value >= 0 ? '+' : ''}${value}%`
          },
          {
            // 排除操作列
            excludeProps: ['actions']
          }
        )

        // 导出为 Excel
        this.$export(
          'excel',
          this.filteredTableData,
          exportColumns,
          `区域贡献值_${this.filterForm.month}`,
          {
            sheetName: '区域贡献值数据'
          }
        )

        this.$message.success('数据导出成功')
      } catch (error) {
        Logger.error('导出失败:', error)
        this.$message.error('导出失败：' + error.message)
      }
    },

    // 搜索
    handleSearch() {
      // 校验查询条件
      if (!this.filterForm.month) {
        this.$message.warning('请选择统计月份')
        return
      }
      this.loadData()
    },

    // 重置
    handleReset() {
      // 重置时设置默认月份，不允许清空
      this.filterForm = {
        month: this.getCurrentMonth(),
        regionId: null
      }
      this.searchKeyword = ''
      this.loadData()
    },

    // 筛选表格数据
    filterTableData() {
      let filtered = [...this.tableData]

      // 按区域筛选
      if (this.filterForm.regionId) {
        filtered = filtered.filter(item => item.id === this.filterForm.regionId)
      }

      // 按关键词搜索
      if (this.searchKeyword) {
        filtered = filtered.filter(item =>
          item.regionName.includes(this.searchKeyword) ||
          item.agentName.includes(this.searchKeyword)
        )
      }

      this.filteredTableData = filtered
      this.pagination.total = filtered.length
      this.pagination.current = 1
    },

    // 搜索关键词
    handleSearchKeyword() {
      this.filterTableData()
    },

    // 按积分排序
    sortByPoints() {
      this.filteredTableData.sort((a, b) => b.points - a.points)
      this.renderChart()
    },

    // 图表类型变化
    handleChartTypeChange() {
      this.renderChart()
    },

    // 查看详情
    handleViewDetail(row) {
      this.selectedRegion = row
      this.detailDialogVisible = true
      this.$nextTick(() => {
        this.renderTrendChart()
      })
    },

    // 查看趋势
    handleViewTrend(row) {
      this.selectedRegion = row
      this.trendDialogVisible = true
      this.$nextTick(() => {
        this.renderTrendAnalysisChart()
      })
    },

    // 渲染趋势图表
    renderTrendChart() {
      const chartDom = document.getElementById('trendChart')
      if (!chartDom) return

      const myChart = echarts.init(chartDom)

      // 模拟月度数据
      const months = ['1月', '2月', '3月', '4月', '5月', '6月']
      const points = [8000, 8500, 9200, 8800, 9500, this.selectedRegion.points]

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: months
        },
        yAxis: {
          type: 'value',
          name: '积分'
        },
        series: [{
          data: points,
          type: 'line',
          smooth: true,
          lineStyle: {
            color: '#409eff'
          },
          itemStyle: {
            color: '#409eff'
          }
        }]
      }

      myChart.setOption(option)
    },

    // 趋势周期变化
    handleTrendPeriodChange() {
      this.renderTrendAnalysisChart()
    },

    // 渲染趋势分析图表
    renderTrendAnalysisChart() {
      const chartDom = document.getElementById('trendAnalysisChart')
      if (!chartDom) return

      const myChart = echarts.init(chartDom)

      // 根据周期生成数据
      let months = []
      let points = []

      if (this.trendPeriod === '3months') {
        months = ['7月', '8月', '9月']
        points = [8500, 9200, this.selectedRegion.points]
      } else if (this.trendPeriod === '6months') {
        months = ['4月', '5月', '6月', '7月', '8月', '9月']
        points = [7800, 8200, 8500, 9200, 9800, this.selectedRegion.points]
      } else if (this.trendPeriod === '12months') {
        months = ['10月', '11月', '12月', '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月']
        points = [6500, 7200, 7800, 8200, 8500, 9200, 7800, 8200, 8500, 9200, 9800, this.selectedRegion.points]
      }

      // 计算分析数据
      this.trendAnalysis = {
        averagePoints: Math.round(points.reduce((sum, p) => sum + p, 0) / points.length),
        maxPoints: Math.max(...points),
        growthRate: points.length > 1 ?
          Math.round(((points[points.length - 1] - points[0]) / points[0]) * 100 * 10) / 10 : 0
      }

      const option = {
        title: {
          text: `${this.selectedRegion.regionName} - 积分贡献趋势`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: months
        },
        yAxis: {
          type: 'value',
          name: '积分数量'
        },
        series: [{
          data: points,
          type: 'line',
          smooth: true,
          lineStyle: {
            color: '#409eff',
            width: 3
          },
          itemStyle: {
            color: '#409eff'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ])
          }
        }]
      }

      myChart.setOption(option)
    },


    // 获取排名标签类型
    getRankTag(rank) {
      if (rank <= 3) return 'success'
      if (rank <= 6) return 'warning'
      return 'info'
    },

    // 获取积分标签类型
    getPointsTag(points) {
      if (points >= 10000) return 'success'
      if (points >= 5000) return 'warning'
      return 'info'
    },

    // 获取积分等级
    getPointsLevel(points) {
      if (points >= 10000) return '优秀'
      if (points >= 5000) return '良好'
      return '一般'
    }
  }
}
</script>

<style scoped>
.region-contribution {
  padding: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.header-actions {
  float: right;
}

.refresh-btn, .export-btn {
  margin-left: 10px;
  border-radius: 6px;
  padding: 8px 16px;
}

.refresh-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.export-btn {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
  border: none;
  box-shadow: 0 4px 15px rgba(86, 171, 47, 0.3);
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  transition: transform 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-2px);
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.overview-card.total .card-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.overview-card.average .card-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.overview-card.top .card-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.overview-card.regions .card-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-content {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-controls {
  float: right;
}

.table-section {
  margin-bottom: 20px;
}

.table-controls {
  float: right;
  display: flex;
  align-items: center;
}

.region-info, .agent-info {
  display: flex;
  align-items: center;
  justify-content: center;
}

.region-info i, .agent-info i {
  margin-right: 5px;
  color: #409eff;
}

.points-display {
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.points-value {
  font-weight: bold;
  color: #303133;
}

.points-tag {
  margin-left: 5px;
}

.growth-positive {
  color: #67c23a;
  font-weight: bold;
}

.growth-negative {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 详情对话框样式已移至公共样式 dialog.scss */
/* 如需特殊样式，可在此处添加覆盖样式 */

.detail-content {
  padding: 0;
}

/* 头部统计卡片 */
.detail-header-stats {
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px 15px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  height: 100%;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 24px;
  color: #fff;
}

.stat-card.primary .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card.success .stat-icon {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
}

.stat-card.warning .stat-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-card.info .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

/* 详细信息卡片 */
.detail-cards-row {
  margin-bottom: 20px;
}

.detail-info-card {
  border-radius: 12px;
  height: 100%;
}

.detail-info-card ::v-deep .el-card__header {
  background: linear-gradient(to right, #f8f9fa, #fff);
  border-bottom: 2px solid #e4e7ed;
  padding: 15px 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}

.card-header i {
  margin-right: 8px;
  font-size: 18px;
  color: #409eff;
}

.info-list {
  padding: 10px 0;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px dashed #e4e7ed;
  transition: all 0.2s ease;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item:hover {
  background: #f8f9fa;
  margin: 0 -10px;
  padding: 12px 10px;
  border-radius: 6px;
}

.info-label {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
}

.info-label i {
  margin-right: 6px;
  color: #909399;
  font-size: 16px;
}

.info-value {
  color: #303133;
  font-weight: 500;
  font-size: 14px;
}

.highlight-item {
  background: linear-gradient(to right, #fff7e6, #fff);
  margin: 0 -10px;
  padding: 15px 10px;
  border-radius: 8px;
  border: 1px solid #ffd591;
}

.highlight-item:hover {
  background: linear-gradient(to right, #fff7e6, #fffbf0);
}

.highlight-value {
  color: #409eff;
  font-weight: bold;
  font-size: 18px;
}

/* 趋势图表卡片 */
.trend-chart-card {
  border-radius: 12px;
}

.trend-chart-card ::v-deep .el-card__header {
  background: linear-gradient(to right, #f8f9fa, #fff);
  border-bottom: 2px solid #e4e7ed;
  padding: 15px 20px;
}

.trend-chart-card ::v-deep .el-card__body {
  padding: 20px;
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 趋势分析对话框样式 */
.trend-dialog ::v-deep .el-dialog__header {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  padding: 20px;
}

.trend-dialog ::v-deep .el-dialog__title {
  color: #fff;
  font-size: 18px;
  font-weight: bold;
}

.trend-dialog ::v-deep .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
  font-size: 20px;
}

.trend-dialog ::v-deep .el-dialog__headerbtn .el-dialog__close:hover {
  color: #f0f0f0;
}

.trend-dialog ::v-deep .el-dialog__body {
  padding: 20px;
  background: #f5f7fa;
}

.trend-content {
  padding: 0;
}

.trend-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.trend-title-section {
  display: flex;
  align-items: center;
}

.trend-title-section i {
  font-size: 24px;
  color: #409eff;
  margin-right: 12px;
}

.trend-title-section h3 {
  color: #303133;
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.trend-controls {
  display: flex;
  align-items: center;
}

.trend-controls ::v-deep .el-radio-button__inner {
  padding: 10px 15px;
}

.trend-controls ::v-deep .el-radio-button__inner i {
  margin-right: 4px;
}

/* 趋势图表包装器 */
.trend-chart-wrapper {
  border-radius: 12px;
  margin-bottom: 20px;
}

.trend-chart-wrapper ::v-deep .el-card__body {
  padding: 20px;
}

/* 趋势分析统计 */
.trend-analysis {
  margin-top: 0;
}

.analysis-card {
  background: #fff;
  border-radius: 12px;
  padding: 25px 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  border: none;
  height: 100%;
}

.analysis-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.analysis-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 28px;
  color: #fff;
}

.analysis-card.average .analysis-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.analysis-card.highest .analysis-icon {
  background: linear-gradient(135deg, #ffd89b 0%, #19547b 100%);
}

.analysis-card.growth .analysis-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.analysis-content {
  flex: 1;
  text-align: left;
}

.analysis-title {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
  font-weight: 500;
}

.analysis-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
  line-height: 1;
}

.analysis-desc {
  font-size: 12px;
  color: #c0c4cc;
  margin-top: 5px;
}

.analysis-value.growth-positive {
  color: #67c23a;
}

.analysis-value.growth-negative {
  color: #f56c6c;
}
</style>
